//document.write("<script language='javascript' src='jquery.min.js'></script>");
//document.scripts[0].src="jquery.min.js"
//var ipPort = "http://localhost:8080";
var ipPort = "http://scrm.cecook.cn";
//var ipPort = "http://localhost:8080";

var obj = {
	id:'1',
	pid:'0',
	name:'',
	sendobj:'',
	sendobjChild:[],
	sendtime:'',
	sendtimeChild:'',
	sendmethod:[],
	rules:'',
	num:0,//人数
	children:[]
};//此对象需要上传到服务器
var currentObj = null;//当前节点对象

function showInfo(){
	currentObj = obj;
	$('#infoName').text($('#activeName').text());	
	$('input:checkbox,input:radio').removeAttr("checked");
	$('input[name="sendtimeDate"]').val('');
	if(currentObj.sendobj){
		$('input:radio[name="sendobj"][value="'+currentObj.sendobj+'"]').prop('checked',true);
	}
	if(currentObj.sendobjChild.length>0){
		for(var i = 0; i < currentObj.sendobjChild.length; i ++){
			$('input:checkbox[name="sendobj'+currentObj.sendobj+'"][value="'+currentObj.sendobjChild[i]+'"]').prop('checked',true);
		}
	}
	if(currentObj.sendtime){
		$('input:radio[name="sendtime"][value="'+currentObj.sendtime+'"]').prop('checked',true);
	}
	if(currentObj.sendtimeChild){
		$('input:radio[name="sendtime"][value="'+currentObj.sendtime+'"] ~ input').val(currentObj.sendtimeChild);
	}
	if(currentObj.sendmethod.length > 0){
		for(var i = 0; i < currentObj.sendmethod.length; i ++){
			$('input:checkbox[name="sendmethod"][value="'+currentObj.sendmethod[i]+'"]').prop('checked',true);
		}
	}
	if(currentObj.rules){
		$('input:radio[name="rules"][value="'+currentObj.rules+'"]').prop('checked',true);
	}
}

var nodes = {
	nameObj:null,
	pid:'',
	text:'1', //区分同级元素
	node:function(){
		return '<td classs="content orgchart" colspan="2" id="td_'+nodes.pid+'"><table>'+
			'<tr id="tr1_'+nodes.pid+'" data-num="'+nodes.text+'">'+
				'<td colspan="0"  id="tr1_'+nodes.pid+'" data-num="'+nodes.text+'">'+
				
					'<div class="box flex-direction width">'+
						'<div class="box item" style="display:block;" id="item_'+nodes.pid+'">'+
						'<div id = "node_'+nodes.pid+'" style="display:none"></div>'+
						'<div id = "DId_'+nodes.pid+'" style="display:none"></div>'+
						
							'<div style="cursor: pointer;" onclick="showFloatingBox(this)" class="con-top"><a style="text-decoration: none;color: white;"><span style="color: #fff;"  id = "Id_'+nodes.pid+'">'+nodes.pid+'</span></a></div>'+
							'<div class="item-bottom con-bottom">'+
								'<p class="con-left"><a href="javascript:nodes.updateNode(\''+nodes.pid+'\');" class="fL_edit">编辑</a></p>'+
								'<div class="con-middle" ><shiro:hasPermission name="sys_dept_member_button"><a href="javascript:nodes.addMemberNode(\''+nodes.pid+'\');" class="fL_add">添加成员</a></shiro:hasPermission></div>'+
								'<div class="con-right"><a href="javascript:void(0);" onclick="nodes.addNode(\''+nodes.pid+'\')">添加子部门</a></div>'+
							'</div>'+    
							'<div class="remove" onclick="nodes.removeNodeBefor(\''+nodes.pid+'\')"></div>'+
						'</div>'+
					'</div>'+
					
//					'<div style="position:absolute;">'+
//					'<div class="popDiv">'+
//    			    '<div class="fix">'+
//                    '<div class="labels">部门名称</div>'+
//                    '<div class="info" > <span id= "hide_dpId'+nodes.pid+'"  ></span></div>'+
//                    '</div>'+
//                    '<div class="fix">'+
//                    '<div class="labels">部门主管</div>'+
//                    '<div class="info" > <span id= "hide_dpLeader'+nodes.pid+'"  ></span></div>'+
//                    '</div>'+
//                    '<div class="fix">'+
//                    '<div class="labels">部门描述</div>'+
//                    '<div class="info"> <span id= "hide_dpDcript_'+nodes.pid+'"  ></span></div>'+
//                    '</div>'+
//                    '<div class="fix">'+
//                    '<div class="labels">创建人</div>'+
//                    '<div class="info"> <span id= "hide_dpUser'+nodes.pid+'"  ></span></div>'+
//                    '</div>'+
//                    '<div class="fix">'+
//                    '<div class="labels">创建时间</div>'+
//                    '<div class="info" > <span id= "hide_dpCreateTime'+nodes.pid+'" ></span></div>'+
//                    '</div>'+
//                    '</div>'+
//                    '</div>'+
                    
				'</td>'+
			'</tr>'+
			'<tr class="lines" id="tr2_'+nodes.pid+'">'+
			'</tr>'+
			'<tr class="lines" id="tr3_'+nodes.pid+'">'+
			'</tr>'+
			'<tr class="nodes" id="tr4_'+nodes.pid+'">'+
			'</tr>'+
		'</table></td>';
	},
	updateNode:function(id){
		var vk = $('#DId_'+id).text();
		
		
		 $.ajax({
			  url: ipPort+"/scrm/api/department/updateBefor",

			  type: "post",
			  
			  async: true,

			  data:{"id":vk},

			  dataType: "json",

			  timeout: 1000,
			  
			  crossDomain: true,

			  error: function(){
				  //alert("nol098");
			  },

			  success: function(data){
				  //alert(1111);
				  var returndata = eval(data);
				  $('#de_name_edit').val(data.name);
				  $('#de_des_edit').val(data.description);
			  }
	        
			  }); 
		
		
		
		
		$('#h4').text('编辑部门');
		//名称和描述显示
		$('#de_name_li').attr('style','display:blcok');
		$('#de_des_li').attr('style','display:blcok');
		$('#add_manger_li').attr('style','display:none');
		$('#de_member_li').attr('style','display:none');
		
		
		
		$('#s_popup_edit').show();
        $('#issue_edit').show();
        
        $('#save_Did').text(vk);
        $('#save_Pid').text(vk);
	},
	addLine:function(id){  // 连接线
		var length = $('#tr4_'+id+'>td').length * 2;
		$('#tr1_'+id+'>td').attr('colspan',length);
		if(length === 0){
			$('#tr2_'+id).html('');
			$('#tr3_'+id).html('');
			return;
		} 
		var downline = '<td colspan="'+length+'"><div class="downLine"></div></td>'
		$('#tr2_'+id).html(downline);
		var topline = '';
		var rightline = '<td class="rightLine">&nbsp;</td>';
		var leftline = '<td class="leftLine">&nbsp;</td>';
		var line = '';
		if(length/2 - 1 > 0){
			for (var i = 0; i < length/2 -1; i++) {
				topline += '<td class="leftLine topLine">&nbsp;</td><td class="rightLine topLine">&nbsp;</td>';
			}
		}
		line = rightline + topline + leftline;
		$('#tr3_'+id).html(line);
	},
	counttree:function(data){
		var c = "_"; // 要计算的字符
		var regex = new RegExp(c, 'g'); // 使用g表示整个字符串都要匹配
		var result = data.match(regex);
		var count = !result ? 0 : result.length;
		return count;
	},
	addNode:function(id){ //添加节点
		
		var D_id = null;
		if (id==1) {
			D_id  = $('#OneDataId').text();
			//alert(D_id+"第一次id显示");
		}else {
			var DID_id = '#DId_'+id;
			//alert(d_id);
			 D_id = $(DID_id).text();
		}
		//alert(D_id+"id");
		
		var strs= new Array(); //定义一数组  
		 strs=id.split("_");
		if (strs.length>4&&strs!=null) {
			alert("最多创建5级子部门");
		}else {
			
		
		//检测是否是在做数据回显
		//alert($('#Pid_Rigth').text());
		if (($('#Pid_Rigth').text())!=null&&($('#Pid_Rigth').text())!="") {
			this.text =$('#Pid_Rigth').text();
			this.pid = id+'_'+this.text;
			
			console.log("文本值为"+this.text+"pid值为"+this.pid);
			$('#Pid_Rigth').text("");
		}else {
			this.text = $('#tr1_'+id).data('num');
			this.pid = id+'_'+$('#tr1_'+id).data('num');
			//alert("测试"+this.text);没有经过这里
		}
		/************************************/
		$('#tr4_'+id).append(this.node);
		this.addLine(id);
		
		console.log("ce"+this.text);
		$('#tr1_'+id).data('num',parseInt(this.text)+1);
		
		if(this.counttree(this.pid) == 1){
			$('#item_' + this.pid).css('background','#03a9f4');
		}else if(this.counttree(this.pid) == 2){
			$('#item_' + this.pid).css('background','#fd7167');
		}

		//添加属性值
		this.addPrototype(id);
		var node_id = '#node_'+nodes.pid;
		$(node_id).text(nodes.pid);
		
				
		 $.ajax({
			  url: ipPort+"/scrm/api/department/create",

			  type: "post",
			  
			  crossDomain: true,
			  
			  async: true,

			  data:{"node":nodes.pid,"parent_id":D_id},

			  dataType: "json",

			  timeout: 1000,

			  error: function(){
				 // alert("nol");
			  },

			  success: function(data){
				var d_id = "#DId_"+data.bak1;
				var dpid = "#Id_"+data.bak1;
  				//alert(d_id);
  			    $(d_id).text(data.id);
  			    $(dpid).text(data.name);
  			   // alert($(d_id).text()+"as");
  			   // window.location.reload();
			  }
	         
			  }); 
		 
    	   
		
		}//部门限定
	},
	
	removeNodeBefor:function(id){
		$('#save_dp_id').text(id);
		
		$('.s_popup_box').removeClass("hide");
		$('.s_popup_box').addClass("show");
		$('.s_popup_detailed').removeClass("hide");
		$('.s_popup_detailed').addClass("show");
		
		
	},
	
	removeNode:function(id){ //删除节点
		
		
		var departmentId=  $('#DId_'+id).text();
		//alert(departmentId);
//		$.post(
//				{
//					"id":departmentId
//				},
//				
//				function(data){
//					if(data.error_code == '1'){
//						alert(data.error_msg);
//					}else{
//						var parid = $('#td_'+id).closest('tr')[0].id.replace('tr4_','');
//						$('#td_'+id).remove();
//						nodes.addLine(parid);
//						nodes.removeElemnt(id,obj);
//					}
//		},"json");
		
		
		 $.ajax({
			  url: ipPort+"/scrm/api/department/delete",

			  type: "post",
			  
			  crossDomain: true,
			  
			  async: true,

			  data:{"id":departmentId},

			  dataType: "json",

			  timeout: 1000,

			  error: function(){},

			  success: function(data){
				  if(data.error_code == '1'){
						alert(data.error_msg);
					}else{
						var parid = $('#td_'+id).closest('tr')[0].id.replace('tr4_','');
						$('#td_'+id).remove();
						nodes.addLine(parid);
						nodes.removeElemnt(id,obj);
					}
			   }
			  }); 
		
		
	},
	addPrototype:function(id){//添加属性对象
		var nodeObj = {
			id:this.pid,
			pid:id,
			name:'',
			sendobj:'',
			sendobjChild:[],
			sendtime:'',
			sendtimeChild:'',
			sendmethod:[],
			rules:'',
			num:0,
			children:[]
		};
		this.findElement(id,obj,nodeObj);
		$('#item_'+this.pid).on('click',function(e){
			var id = this.id.replace('item_','');
			nodes.findNode(id,obj);
			var name = currentObj.name ? currentObj.name : '还未选择活动名';
			$('#infoName').text(name);

			$('input:checkbox,input:radio').removeAttr("checked");
			$('input[name="sendtimeDate"]').val('');
			if(currentObj.sendobj){
				$('input:radio[name="sendobj"][value="'+currentObj.sendobj+'"]').prop('checked',true);
			}
			if(currentObj.sendobjChild.length>0){
				for(var i = 0; i < currentObj.sendobjChild.length; i ++){
					$('input:checkbox[name="sendobj'+currentObj.sendobj+'"][value="'+currentObj.sendobjChild[i]+'"]').prop('checked',true);
				}
			}
			if(currentObj.sendtime){
				$('input:radio[name="sendtime"][value="'+currentObj.sendtime+'"]').prop('checked',true);
			}
			if(currentObj.sendtimeChild){
				$('input:radio[name="sendtime"][value="'+currentObj.sendtime+'"] ~ input').val(currentObj.sendtimeChild);
			}
			if(currentObj.sendmethod.length > 0){
				for(var i = 0; i < currentObj.sendmethod.length; i ++){
					$('input:checkbox[name="sendmethod"][value="'+currentObj.sendmethod[i]+'"]').prop('checked',true);
				}
			}
			if(currentObj.rules){
				$('input:radio[name="rules"][value="'+currentObj.rules+'"]').prop('checked',true);
			}
			console.log(obj);
		});
	},
	findNode:function(id,node){
		var nodeChild = node.children;
		for(var i = 0; i < nodeChild.length; i ++){
			if(id == nodeChild[i].id){
				currentObj = nodeChild[i];
				break;
			}else{
				this.findNode(id,nodeChild[i]);
			}
		}
	},
	findElement:function(pid,node,sonNode){
		if(pid == node.id){
			node.children.push(sonNode);
		}else{
			var nodeChild = node.children;
			for(var i = 0; i < nodeChild.length; i ++){
				this.findElement(pid,nodeChild[i],sonNode);
			}
		}
	},
	removeElemnt:function(id,node){
		var nodeChild = node.children;
		for(var i = 0; i < nodeChild.length; i ++){
			if(id == nodeChild[i].id){
				nodeChild.splice(i,1);
				break;
			}else{
				this.removeElemnt(id,nodeChild[i]);
			}
		}
	},
	addMemberNode:function(id){
		var vk = $('#DId_'+id).text();
		//alert("cy:"+vk);
		$('.fL_add').attr("department_id",vk);
		console.log(1111+"进入apps");
		addlm();
	},
	showModel:function(e){
		$('.s_cancel').click(function(){
            $('.s_popup').hide();
            $('.issue').hide();
        });
        $('.s_cancels').click(function(){
            $('.s_popups').hide();
            $('.s_number_list').hide();
        });

        $('.s_popup .issue > span').click(function(){
            $('.s_popup').hide();
            $('.issue').hide();
        });
         $('.s_popups .s_number_list > span').click(function(){
            $('.s_popups').hide();
            $('.s_number_list').hide();
        });
        
        $('.s_popups').show();
        $('.s_number_list').show();
        nameActive = '';
        this.nameObj = e;
        console.log($(e).text());
	}
};

function addName(){

	if(nameActive){
		$(nodes.nameObj).text(nameActive);
		currentObj.name = nameActive;
	}
	$('.s_popups').hide();
    $('.s_number_list').hide();
}

function submitInfo(){ //提交信息
	var sendobj = $('input:radio[name="sendobj"]:checked').val();
	var sendobjChild = [];
	$('input:checkbox[name="sendobj'+sendobj+'"]:checked').each(function(){
		sendobjChild.push(this.value);
	});

	var sendtime = $('input:radio[name="sendtime"]:checked').val();
	if($('input:radio[name="sendtime"]:checked ~ input').length > 0){
		var sendtimeChild = $('input:radio[name="sendtime"]:checked ~ input').val();
	}

	var sendmethod = [];
	$('input:checkbox[name="sendmethod"]:checked').each(function(){
		sendmethod.push(this.value);
	});
	var rules = $('input:radio[name="rules"]:checked').val();
	if(currentObj){
		currentObj.sendobj = sendobj;
		currentObj.sendobjChild = sendobjChild;
		currentObj.sendtime = sendtime;
		currentObj.sendmethod = sendmethod;
		currentObj.rules = rules;
		if(sendtimeChild){
			currentObj.sendtimeChild = sendtimeChild;
		}else{
			currentObj.sendtimeChild = '';
		}
	}
	console.log(obj);
}
var nameActive = '';
// 选择model
function chooseActive(){
	var target = event.target;
	if(target.src){
		$('.s_fk_pic1').each(function(e){
			this.src = '../images/s_check_no.png';
		});
		target.src = '../images/s_check.png';
	}
	nameActive = $(target).closest('td').next().text();
}

function update_depart(id){
	alert(id);
}


function showFloatingBox(data){
	var id = $(data).find('span').attr("id");
	console.log(id);
	var strs= new Array(); //定义一数组  
	strs=id.split("Id_");
	var bak1;
	for (var i= 0; i < strs.length; i++) {
		if (i==1) {
			bak1= strs[1];
		}
	}
	  $("#hide_dpId").text("");
	  $("#hide_dpDcript_").text("");
	  $("#hide_dpLeader").text("");
	  $("#hide_dpCreateTime").text("");
	  $("#hide_dpUser").text("");
	console.log(bak1);
	 $.ajax({
		  url: ipPort+"/scrm/api/department/showflow",

		  type: "post",
		  
		  async: true,

		  data:{"bak1":bak1},

		  dataType: "json",

		  timeout: 1000,
		  
		  crossDomain: true,

		  error: function(){
			  //alert("nol098");
		  },

		  success: function(data){
			  //alert(1111);
			  var returndata = eval(data);
			  //alert(returndata[0].name);
			  //$('#hide_dpId').text(returndata[0].name);
//				      
			  
			  
			          var hide_dpId = "#hide_dpId";
			          var hide_dpDcript = "#hide_dpDcript_";
			          var hide_dpLeader = "#hide_dpLeader";
			    
			          var hide_dpCreateTime = "#hide_dpCreateTime";
			          
			         // alert(returndata[0].description);
					 
					  if ((returndata[0].name)!=null&&(returndata[0].name)!="") {
						  $(hide_dpId).text(returndata[0].name);
					}
					  if ((returndata[0].description)!=null&&(returndata[0].description)!="") {
						  $(hide_dpDcript).text(returndata[0].description);
					}
					
					 if ((returndata[0].sysUser)!=null&&(returndata[0].sysUser)!="") {
						 $(hide_dpLeader).text(returndata[0].sysUser.name);
					}
					
					
					 if ((returndata[0].bak2)!=null&&(returndata[0].bak2)!="") {
						 var createtime =returndata[0].bak2;
						 $(hide_dpCreateTime).text(createtime);
					}
		     }
        
		  }); 
	 
	 $.ajax({
		  url: ipPort+"/scrm/api/department/showflowforuser",

		  type: "post",
		  
		  async: true,

		  data:{},

		  dataType: "json",

		  timeout: 1000,
		  
		  crossDomain: true,

		  error: function(){
			  //alert("nol098");
		  },

		  success: function(data){
			  
			  var returndata = eval(data);
			  //alert(returndata.name);
			  var hide_dpUser = "#hide_dpUser";
			  $(hide_dpUser).text(returndata.name);
			  
		    }
        
	}); 
  
  //$(data).parents('td[id="tr1_'+bak1+'"]').find('.popDiv').stop().fadeIn();
	$('#hide_dp').removeClass("hide");
	$('#hide_dp').addClass("show");
	$('#hide_dp2').removeClass("hide");
	$('#hide_dp2').addClass("show");
}




$(function(){
	$('#i_close').click(function(){
		$('#hide_dp').removeClass("show");
		$('#hide_dp').addClass("hide");
		$('#hide_dp2').removeClass("show");
		$('#hide_dp2').addClass("hide");
		  $("#hide_dpId").text("");
		  $("#hide_dpDcript_").text("");
		  $("#hide_dpLeader").text("");
		  $("#hide_dpCreateTime").text("");
		  $("#hide_dpUser").text("");
		
	});
	
	
//	$(document).on('click',"td[data-num]",function(){
//		var id = $(this).prop("id");
//		var strs= new Array(); //定义一数组  
//		strs=id.split("tr1_");
//		var bak1;
//		for (var i= 0; i < strs.length; i++) {
//			if (i==1) {
//				bak1= strs[1];
//			}
//		}
//		console.log(bak1);
//			 $.ajax({
//
//				  type: "post",
//				  
//				  async: true,
//	
//				  data:{"bak1":bak1},
//	
//				  dataType: "json",
//	
//				  timeout: 1000,
//				  
//				  crossDomain: true,
//	
//				  error: function(){
//					  //alert("nol098");
//				  },
//	
//				  success: function(data){
//					  //alert(1111);
//					  var returndata = eval(data);
//					  //alert(returndata[0].name);
//					  //$('#hide_dpId').text(returndata[0].name);
////						
//					          var hide_dpId = "#hide_dpId"+bak1;
//					          var hide_dpDcript = "#hide_dpDcript_"+bak1;
//					          var hide_dpLeader = "#hide_dpLeader"+bak1;
//					    
//					          var hide_dpCreateTime = "#hide_dpCreateTime"+bak1;
//					         // alert(returndata[0].description);
//							  $(hide_dpId).text(returndata[0].name);
//							  if ((returndata[0].description)!=null&&(returndata[0].description)!="") {
//								  $(hide_dpDcript).text(returndata[0].description);
//							}
//							
//							 if ((returndata[0].sysUser)!=null&&(returndata[0].sysUser)!="") {
//								 $(hide_dpLeader).text(returndata[0].sysUser.name);
//							}
//							
//							
//							 if ((returndata[0].createTime)!=null&&(returndata[0].createTime)!="") {
//								 var createtime =returndata[0].createTime;
//								
//								 $(hide_dpCreateTime).text(returndata[0].createTime);
//							}
//				     }
//		         
//				  }); 
//			 
//			 $.ajax({
//
//				  type: "post",
//				  
//				  async: true,
//	
//				  data:{},
//	
//				  dataType: "json",
//	
//				  timeout: 1000,
//				  
//				  crossDomain: true,
//	
//				  error: function(){
//					  //alert("nol098");
//				  },
//	
//				  success: function(data){
//					  
//					  var returndata = eval(data);
//					  //alert(returndata.name);
//					  var hide_dpUser = "#hide_dpUser"+bak1;
//					  $(hide_dpUser).text(returndata.name);
//				    }
//		         
//			}); 
//		
//		$(this).find('.popDiv').stop().fadeIn();
//    });
//    $(document).on('mouseleave',"td[data-num]",function(){
//        $(this).find('.popDiv').stop().fadeOut();
//    });
});